package edu.ccut.saturn.basecomponent.database.impl.db2.builder;

import java.util.ArrayList;
import java.util.List;

import edu.ccut.saturn.basecomponent.database.ISaturnSQL;
import edu.ccut.saturn.basecomponent.database.SaturnSQLBuilderFactory;
import edu.ccut.saturn.basecomponent.database.impl.AbstractSelectSQLBuilder;
import edu.ccut.saturn.basecomponent.database.impl.SaturnSQL;
import edu.ccut.saturn.basecomponent.database.util.SaturnDataUtil;
import edu.ccut.saturn.component.IDataInfo;
import edu.ccut.saturn.component.IDataItem;

public class DB2SelectCountSQLBuilder extends AbstractSelectSQLBuilder {

	private final String SQL_SELECT_COUNT = "SELECT MAX(ROWNUM) FROM(SELECT ROWNUMBER() OVER() ROWNUM FROM @result@)";
	private final CharSequence SQL_RESULT_PLACEHOLDER = "@result@";
	
	@Override
	public ISaturnSQL build2(String fullKey, String condition) throws Exception {
		return this.build2(fullKey, condition, null);
	}
	
	public ISaturnSQL build2(String fullKey, String condition, String tableWord) throws Exception {

		SaturnSQL saturnsql = new SaturnSQL();

		saturnsql.setSql(getSql(fullKey, condition, tableWord));
		saturnsql.setDBtype(this.getDatabaseType());
		saturnsql.setOperationType(this.getOperationType());
		saturnsql.setSaturnData(null);
		saturnsql.setSaturnDataFullKey(fullKey);

		return saturnsql;
	}

	private String getSql(String fullKey, String condition, String tableWord) {
		
		StringBuffer sqlResult = new StringBuffer();
		IDataInfo dataInfo = SaturnDataUtil.getDataInfo(fullKey);
		String tempSQL = dataInfo.getSqlStr();
		if (null != tempSQL && !"".equals(tempSQL)) {
			sqlResult.append("(");
			sqlResult.append(tempSQL);
			if (null != condition){
				sqlResult.append(condition.replace("WHERE", " AND"));
			}
			sqlResult.append(") A");
		} else {
			if (null != tableWord && !"".equals(tableWord.trim())){
				sqlResult.append(tableWord);
			} else {
				sqlResult.append(addTableNames(dataInfo));
			}
			if (null != condition){
				sqlResult.append(" ").append(condition);
			}
		}
		String result = this.SQL_SELECT_COUNT;
		return result.replace(SQL_RESULT_PLACEHOLDER, sqlResult.toString());
	}

	private StringBuffer addTableNames(IDataInfo dataInfo) {
		
		StringBuffer result = new StringBuffer();
		List<String> tableNamelist = new ArrayList<String>();
	
		for (String key : dataInfo.keySet()) {
			IDataItem dataItem = dataInfo.getDataItem(key);
			String tableName = dataItem.getTableName();
			if (null != tableName && !"".equals(tableName.trim())
					&& !tableNamelist.contains(tableName)) {
				
				tableNamelist.add(tableName);
				result.append(tableName).append(" ,");
			}
		}
		return result.deleteCharAt(result.length() - 1);
	}

	@Override
	protected String getDatabaseType() {
		return SaturnSQLBuilderFactory.DB2;
	}

	@Override
	protected String getOperationType() {
		return ISaturnSQL.SELECT_COUNT_OPERATION;
	}

}
